package com.peng.leetcode.array;

/**
 * IslandPerimeter
 * 463. 岛屿的周长
 * https://leetcode.cn/problems/island-perimeter/
 *
 * @author: lupeng6
 * @create: 2023/2/19 10:01
 */
public class IslandPerimeter {
    public int islandPerimeter(int[][] grid) {
        int ans = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1) {
                    ans += judge(grid, i, j);
                }
            }
        }
        return ans;
    }

    private int judge(int[][] grid, int i, int j) {
        int[][] operations = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
        int len = 4;
        for (int[] operation : operations) {
            int a = i + operation[0];
            int b = j + operation[1];
            if (a >= 0 && a < grid.length && b >= 0 && b < grid[0].length && grid[a][b] == 1) {
                len--;
            }
        }
        return len;
    }
}
